<?php
namespace app\wechat\controller;

use think\Request;
use think\Cookie;
use think\View;
use think\Log;

import('phpqrcode/phpqrcode', VENDOR_PATH);
import('weixin/weixin', VENDOR_PATH);

//微信appid
define('WXAPPID','wxd65849ebe359e61e');
//微信AppSecret
define('APPSECRET','414fb50745e442239a88394db542fc9d');

/**
 * 接口服务
 * 招商·蚂蚁·商户 聚合支付
 *
 */
class Zspay extends Common
{
    // 定义全局常量
    protected $config;
    //dev开发环境
    protected $env = APP_ENV;

    public function __construct() {
        parent::__construct();
        $this->config = config('zspay.' . $this->env);

    }


    /**
     * 商户生成二维码后，用户扫码，进入填写付款页面。
     *
     */
    public function userPayment()
    {
        $data = Request::instance()->get();

        //查询商户名称
        $partner = $this->getWS('credit', 'PartnersOrder@partnerInfo', ['partner_id' => $data['partner_id']]);
        if ($partner['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取商户失败,请联系管理员']);
        }
        //查询商户下的产品
        $result = $this->getWS('credit', 'product@productArrZs', ['partner_id' => $data['partner_id']]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取产品失败,请联系管理员']);
        }

        if(IsWeixinOrAlipay() == 'WeiXin'){
            //如果是微信扫码获取用户微信openid
            if(empty($data['openid'])){
                $redirect_uri = "http://release.weixin.mayi121.com/pay.openid?partner_id=".$data['partner_id'];
                $scope = "snsapi_base";
                header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd65849ebe359e61e&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect");
                exit;
            }

            header("Location:http://test.weixin2.mayi121.com/pay/zsPrePay.html?openid={$data['openid']}&partner_id={$data['partner_id']}");
            exit;
        }
        print_r('OK');exit;
        //http://test.weixin2.mayi121.com/pay/prepay.html?openid=oHRftt6_uBpTa1q81GcHl1OIMwf0&appid=tcVDa8oe4WZ0CBAY&partner_id=15&services=2
//        return view('pay/zsPrePay',['data' => $result['result'],'partner'=>$partner['result']]);
    }

    /**
     * 获取商户和产品信息
     *
     */
    public function getMerchant()
    {
        $data = Request::instance()->post();

        //查询商户名称
        $partner = $this->getWS('credit', 'PartnersOrder@partnerInfo', ['partner_id' => $data['partner_id']]);
        if ($partner['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取商户失败,请联系管理员']);
        }
        //查询商户下的产品
        $result = $this->getWS('credit', 'product@productArrZs', ['partner_id' => $data['partner_id']]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取产品失败,请联系管理员']);
        }

        return $this->parse_data(['code' => 2000, 'data' => ['partners' => $partner['result'],'product'=>$result['result']]]);
    }

    /**
     * 下单页面
     *
     */
    public function payOrder(){

        $param = Request::instance()->post();

        $params = [];
        foreach($param as $k=>$v){
            $params[$k] = $this->xaddslashes($v);
        }

//        $params = array(
//            'openid'        =>'oHRftt6_uBpTa1q81GcHl1OIMwf0',
//            'partnerId'     => '184',
//            'services'      => 1,
//            'amount'        => '8500.00',
//            'name'          => '张三',
//            'phone'         => '18301099036',
//            'note'          => '水电费',
//            'productId'     => '241',
//            'product_name'  => '非标短跑',
//        );

        //验证信息
        if(empty($params['openid']) || empty($params['partnerId']) || empty($params['services']) ||
            empty($params['amount']) || empty($params['name']) || empty($params['phone'])){
            return $this->parse_data(['code' => 5000, 'msg' => '数据不能为空']);
        }

        if(!is_numeric($params['amount'])){
            return $this->parse_data(['code' => 5000, 'msg' => '金额填写有误']);
        }

        if(!preg_match("/^1[34578]{1}\d{9}$/",$params['phone'])){
            return $this->parse_data(['code' => 5000, 'msg' => '手机填写有误']);
        }

        //你已经选择了课程，不可以选择其他课程。
        $order = array(
            'partner_id'    =>$params['partnerId'],
            'phone'         =>$params['phone'],
            'status'        =>'2000',
        );
        $partnersOrderArr = $this->getWS('credit', 'PartnersOrder@partnerSelect', $order);
        if($partnersOrderArr['result'][0]['product_id'] != $params['productId']){
            return $this->parse_data(['code' => 5000, 'msg' => '你已经选择了课程，不可以选择其他课程']);
        }

        //查询商户信息
        $partners = $this->getWS('credit', 'product@checkPartners', ['partner_id' => $params['partnerId']]);
        if ($partners['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取商户失败,请联系管理员']);
        }

        //查询产品信息
        $product = $this->getWS('credit', 'product@productInfoZs', ['p_id' => $params['productId']]);
        if ($product['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取产品失败,请联系管理员']);
        }

        //生成订单号
        $order_num = 'MY'.date('YmdHis').mt_rand(1000,9999);

        //输入金额
        $p_amount = substr(sprintf("%.3f",$params['amount']),0,-1);

        //总金额
        $p_set_amount = substr(sprintf("%.3f",$product['result']['p_set_amount']),0,-1);
        //剩余金额
        $balance = $p_set_amount-$p_amount;
        $p_balance = substr(sprintf("%.3f",$balance),0,-1);
        //最小金额
        $p_min_amt = substr(sprintf("%.3f",$product['result']['p_min_amt']),0,-1);

        $zhaoshangPay = array();
        //验证金额是否是走账单管理(判断输入的金额是否小于并且剩余的金额大于等于最小金额)
        if($p_amount < $p_set_amount && $p_balance >=$p_min_amt){//-------走账单管理

            //判断是微信还是现金，如果是微信就调用招行的支付接口
            if($params['services'] == 1){//微信
                $services = '1';
                //调用招行接口支付
                $data = array(
                    'order_num'     => $order_num,//订单号
                    'partner_xtb_no'=> $partners['result']['partner_xtb_no'],//支付通道报备号
                    'productName'   => $params['product_name'],//课程名称
                    'payMoney'      => $params['amount'], //支付金额
                    'channelPay'    => $params['services'], //支付渠道
                    'openid'        => $params['openid'], //用户openid
                    'partnerId'     => $params['partnerId'], //商家ID
                );
//                print_r($data);exit;
                $zhaoshangPay = $this->getWS('channel', 'ZhaoshangPay@unifiedPayment', $data);

                if ($zhaoshangPay['status'] != '2000') {
                    return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
                }

            }else if($params['services'] == 2){//现金
                $services = '3';
            }

        }else if($p_amount < $p_set_amount && $p_balance < $p_min_amt){//您的剩余支付金额小于账单管理范围最小金额，是否继续？

            if($params['services'] == 1){
                $services = '1';
                //调用招行接口支付
                $data = array(
                    'order_num'     => $order_num,//订单号
                    'partner_xtb_no'=> $partners['result']['partner_xtb_no'],//支付通道报备号
                    'productName'   => $params['product_name'],//课程名称
                    'payMoney'      => $params['amount'], //支付金额
                    'channelPay'    => $params['services'], //支付渠道
                    'openid'        => $params['openid'], //用户openid
                    'partnerId'     => $params['partnerId'], //商家ID
                );
//                print_r($data);exit;
                $zhaoshangPay = $this->getWS('channel', 'ZhaoshangPay@unifiedPayment', ['data' => $data]);
                if ($zhaoshangPay['status'] != '2000') {
                    return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
                }
            }else if($params['services'] == 2){//现金
                $services = '3';
            }
        }else if($p_amount >= $p_set_amount){//print_r("直接过不走账单管理");exit;

            if($params['services'] == 1){
                $services = '1';
                //调用招行接口支付
                $data = array(
                    'order_num'     => $order_num,//订单号
                    'partner_xtb_no'=> $partners['result']['partner_xtb_no'],//支付通道报备号
                    'productName'   => $params['product_name'],//课程名称
                    'payMoney'      => $params['amount'], //支付金额
                    'channelPay'    => $params['services'], //支付渠道
                    'openid'        => $params['openid'], //用户openid
                    'partnerId'     => $params['partnerId'], //商家ID
                );

                $zhaoshangPay = $this->getWS('channel', 'ZhaoshangPay@unifiedPayment', ['data' => $data]);
                if ($zhaoshangPay['status'] != '2000') {
                    return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
                }
            }else if($params['services'] == 2){//现金
                $services = '3';
            }

        }else{
            return $this->parse_data(['code' => 5000, 'msg' => '金额有误,请联系管理员']);
        }

        // 记录支付流水
        $transactionPay = array(
            'channel'           => '2',//第三方通道：1学通宝，2招商 3工商
            'appid'             => $partners['result']['partner_xtb_no'],//商户报备号
            'partner_id'        => $params['partnerId'],//商户id
            'order_num'         => $order_num,//订单号
            'services'          => $services,//服务类型
            'amount'            => $p_amount,//交易金额
            'product_id'        => $params['productId'],//课程id
            'product_name'      => $params['product_name'],//产品名称
            'name'              => $params['name'],//姓名
            'phone'             => $params['phone'],//手机号
            'note'              => $params['note'],//备注
            'status'            => '1000',//状态：1000初始，2000成功，3000等待，4000失败
            'add_time'          => date('Y-m-d H:i:s'),//下单时间
            'clientip'          => getenv("REMOTE_ADDR"),//请求IP地址
            'tradeOrderNo'      => $zhaoshangPay['result']['nowPayOrderNo'],//招商流水号
            'open_id'           => $params['openid'],//微信用户唯一标识
            'synchronize_info'  => serialize($zhaoshangPay['result']),//同步返回信息
        );

        $partnersOrder = $this->getWS('credit', 'PartnersOrder@partnerInsert', $transactionPay);

        if ($partnersOrder['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '下单失败,请联系管理员']);
        }
        return $this->parse_data(['code' => 2000, 'msg' => '下单成功', 'data'=> $transactionPay]);
    }


    /**
     * 绑定银行卡(验证四要素)
     * @Author   hanming
     * @Email    ming.han@mayi121.com
     * @DateTime 2018-08-14T16:54:36+0800
     * @param    [type]
     * @return   [type]
     */
    public function bindBank(){

        $params = Request::instance()->post();

//        $params = array(
//            'openid'      => 'oHRftt6_uBpTa1q81GcHl1OIMwf0',
//            'partner_id'  => '184',
//            'name'        => '张三',
//            'phone'       => '18301099036',
//            'bank_num'    => '6212250200007417288',
//            'identity_num'=> '142731198807250951',
//        );

        //生成默认密码
        $password = substr($params['phone'],-6);

        //生成u_code
        $users = $this->getWS('ucenter', 'users@reg', ['userName' => $params['phone'], 'userPwd' => $password, 'openId' => $params['openid']]);

        if(empty($users['result']['u_code'])){
            return $this->parse_data(['code' => 5000, 'msg' => '获取用户信息失败']);
        }

        //获取银行卡名称
        $result = $this->getWS('channel', 'Pay@bankInfo', ['card_no'=>$params['bank_num']]);

        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '获取银行卡信息失败']);
        }
        $info = $result['result'];
        if($info['ret_code'] != '0000'){
            return $this->parse_data(['code' => 5000, 'msg' => '您输入的卡号有误']);
        }
        if($info['card_type'] == '3'){
            return $this->parse_data(['code' => 5000, 'msg' => '不支持信用卡']);
        }
        if(empty(config('dict.bank_list')[$info['bank_code']])){
            return $this->parse_data(['code' => 5000, 'msg' => '不支持该银行卡']);
        }

        //查询用户姓名和身份证号
        $res  = $this->getWS('ucenter', 'users@userInfo', ['u_code' =>  $users['result']['u_code']]);

        if($res['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '获取用户信息失败']);
        }

        //判断是否绑卡成功，如果成功，跳过绑卡
        if($res['result']['ub_card_no'] && $res['result']['ub_bank_name'] && $res['result']['ub_phone']){
            return $this->parse_data(['code' => 2000, 'msg' => '验证四要素成功', 'data'=> $res['result']]);
        }

        //绑卡
        $condition['u_code']    = $users['result']['u_code'];//u_code
        $condition['cardNo']    = $params['bank_num'];//银行卡号
        $condition['realName']  = $params['name'];//真实姓名
        $condition['identNo']   = $params['identity_num'];//身份证号
        $condition['phone']     = $params['phone'];//手机号
        $condition['bankName']  = $info['bank_name'];//银行卡名称
        $res2 = $this->getWS('ucenter', 'bank@bankBind', $condition);

        if($res2['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '绑卡失败，银行卡号校验不一致']);
        }

        return $this->parse_data(['code' => 2000, 'msg' => '验证四要素成功', 'data'=> $res['result']]);
    }

    /**
     * 获取微信的openid
     *
    */
    public function getOpen(){
        $code = Request::instance()->get();
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".WXAPPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
        $result = $this->curlOpen($url);
        $res = json_decode($result, true);

        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";
        $result = $this->curlOpen($url);
        $res = json_decode($result,true);

        echo $res;exit;
    }


    //curl函数
    public function curlOpen ($url, $cfg)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        if ($cfg['ssl']) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $cfg['post']);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
//        print_r($info);exit;
        curl_close($ch);

        return $result;
    }

    /**
     * 返回调用,不用这个parse_data，是因为他返回的还得转换
     *
     */
    public function outputJson($data, $exit = false)
    {
        ob_end_clean();
        isset($GLOBALS['setToken']) ? $data = array_merge($data, $GLOBALS['setToken']) : null;
        $json = json_encode($data);
        print_r($json);
        if ($exit)
            exit;
    }


    /**
     * 微信付款成功页面。
     *
     */
    public function wxPaySuccess()
    {

        $data = Request::instance()->get();
        //获取蚂蚁订单号
        $orderNo = $data['orderNo'];

        $partnerWhere = array(
            'order_num' => $orderNo,
        );
        $orderPartnerInfo = $this->getWS('credit', 'PartnersOrder@orderPartnerInfo', $partnerWhere);

        $return = array(
            'amount'=>$orderPartnerInfo['result']['amount'],
            'payee'=> $orderPartnerInfo['result']['partner_name'],
            'paytype'=> '微信',
            'paytime'=> $orderPartnerInfo['result']['add_time'],
        );
        return view('pay/zsOrderSuccess',['data' => $return]);
    }

    /**
     * 微信付款JS-SDK
     *
     */
    public function getSignature()
    {
        $data = Request::instance()->get();

        //生成wx.config
        $weixin =  new \Lib_Weixin();
        $tokenarr = $weixin->getAccessToken(WXAPPID, APPSECRET);
        $jsapi_ticket = $weixin->getJsApiTicket($tokenarr['access_token']);
        $nonceStr = getRandomChar();
        $time = time();
        $signature = sha1("jsapi_ticket=".$jsapi_ticket['ticket']."&noncestr=".$nonceStr."&timestamp=".$time."&url=".$data['url']);

//        $wx_config = "wx.config({
//						debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//						appId: '".WXAPPID."', // 必填，公众号的唯一标识
//						timestamp: ".$time.", // 必填，生成签名的时间戳
//						nonceStr: '".$nonceStr."', // 必填，生成签名的随机串
//						signature: '".$signature."',// 必填，签名，见附录1
//						jsApiList: ['closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
//					});";
//        print_r($wx_config);exit;
        $wx_config = array(
            'appId'     => WXAPPID,
            'timestamp' => $time,
            'nonceStr'  => $nonceStr,
            'signature' => $signature,
        );

        $out = array(
            'status' => 2000,
            'msg' => '成功',
            'result' => $wx_config,
        );
        $this->outputJson($out,true);

    }








}
